// src/services/areaService.js
// 行政区划数据服务 - 支持省市区街道四级联动
class AreaService {
  constructor() {
    this.allData = []
    this.regionData = []
    this.isInitialized = false
  }

  // 初始化数据
  async initData() {
    if (this.isInitialized) {
      return true
    }

    try {
      const response = await import('@/assets/data.json')
      this.allData = response.default || response
      console.log('加载行政区划数据成功:', this.allData.length, '条记录')
      
      // 处理数据
      this.processRegionData()
      this.isInitialized = true
      return true
    } catch (error) {
      console.error('加载行政区划数据失败:', error)
      return false
    }
  }

  // 处理地区数据为级联选择器格式
  processRegionData() {
    const provincesMap = new Map()
    const citiesMap = new Map()
    const districtsMap = new Map()

    // 第一遍：处理省份数据
    this.allData.forEach(item => {
      if (item.city === 0 || item.city === '00') {
        const provinceCode = item.province + '0000'
        if (!provincesMap.has(provinceCode)) {
          provincesMap.set(provinceCode, {
            value: provinceCode,
            label: item.name,
            children: []
          })
        }
      }
    })

    // 第二遍：处理城市数据
    this.allData.forEach(item => {
      if ((item.city !== 0 && item.city !== '00') && (item.area === 0 || item.area === '00')) {
        const provinceCode = item.province + '0000'
        const cityCode = item.province + item.city + '00'
        
        if (!citiesMap.has(cityCode)) {
          const city = {
            value: cityCode,
            label: item.name,
            children: []
          }
          citiesMap.set(cityCode, city)
          
          const province = provincesMap.get(provinceCode)
          if (province) {
            province.children.push(city)
          }
        }
      }
    })

    // 第三遍：处理区县数据
    this.allData.forEach(item => {
      if ((item.area !== 0 && item.area !== '00') && item.town === 0) {
        const cityCode = item.province + item.city + '00'
        const districtCode = item.province + item.city + item.area
        
        if (!districtsMap.has(districtCode)) {
          const district = {
            value: districtCode,
            label: item.name,
            children: []
          }
          districtsMap.set(districtCode, district)
          
          const city = citiesMap.get(cityCode)
          if (city) {
            city.children.push(district)
          } else {
            // 如果城市不存在，直接挂到省份下
            const provinceCode = item.province + '0000'
            const province = provincesMap.get(provinceCode)
            if (province) {
              province.children.push(district)
            }
          }
        }
      }
    })

    // 第四遍：处理街道数据
    this.allData.forEach(item => {
      if (item.town !== 0) {
        const districtCode = item.province + item.city + item.area
        
        const street = {
          value: item.code,
          label: item.name,
          children: []
        }
        
        // 不使用streetsMap去重，直接添加到对应的区县下
        const district = districtsMap.get(districtCode)
        if (district) {
          district.children.push(street)
        }
      }
    })

    this.regionData = Array.from(provincesMap.values())
  }

  // 获取级联选择器数据
  getRegionData() {
    return this.regionData
  }

  // 根据代码数组获取地址文本
  getAddressText(codes) {
    if (!codes || !Array.isArray(codes) || codes.length === 0) return ''
    
    let currentLevel = this.regionData
    const names = []
    
    for (const code of codes) {
      const item = currentLevel.find(item => item.value === code)
      if (!item) break
      names.push(item.label)
      currentLevel = item.children || []
    }
    
    return names.join(' / ')
  }

  // 根据编码查找对应的中文名称
  findRegionName(code) {
    if (!code) return ''
    
    const findName = (data, targetCode) => {
      if (!Array.isArray(data)) return ''

      for (const item of data) {
        if (item.value === targetCode) {
          return item.label
        }
        if (item.children) {
          const result = findName(item.children, targetCode)
          if (result) {
            return result
          }
        }
      }
      return ''
    }

    return findName(this.regionData, code)
  }

  // 根据省市区名称查找对应的编码数组（用于回显）
  findAddressCodes(provinceName, cityName, districtName, streetName) {
    const codes = []
    
    if (!provinceName) return codes
    
    // 查找省份
    const province = this.regionData.find(p => 
      p.label === provinceName || 
      provinceName.includes(p.label) || 
      p.label.includes(provinceName)
    )
    
    if (province) {
      codes.push(province.value)
      
      // 查找城市
      if (cityName && province.children) {
        const city = province.children.find(c => 
          c.label === cityName || 
          cityName.includes(c.label) || 
          c.label.includes(cityName)
        )
        
        if (city) {
          codes.push(city.value)
          
          // 查找区县
          if (districtName && city.children) {
            const district = city.children.find(d => 
              d.label === districtName || 
              districtName.includes(d.label) || 
              d.label.includes(districtName)
            )
            
            if (district) {
              codes.push(district.value)
              
              // 查找街道
              if (streetName && district.children) {
                const street = district.children.find(s => 
                  s.label === streetName || 
                  streetName.includes(s.label) || 
                  s.label.includes(streetName)
                )
                
                if (street) {
                  codes.push(street.value)
                }
              }
            }
          }
        }
      }
    }
    
    return codes
  }

  // 处理表单地址数据（将级联选择器值转换为单独的字段）
  processFormAddress(form, addressField = 'nativeAddress', prefix = 'native') {
    const address = form[addressField]
    
    if (!address || !Array.isArray(address) || address.length === 0) {
      form[`${prefix}Province`] = ''
      form[`${prefix}City`] = ''
      form[`${prefix}District`] = ''
      form[`${prefix}Street`] = ''
      return
    }

    form[`${prefix}Province`] = address.length >= 1 ? this.findRegionName(address[0]) : ''
    form[`${prefix}City`] = address.length >= 2 ? this.findRegionName(address[1]) : ''
    form[`${prefix}District`] = address.length >= 3 ? this.findRegionName(address[2]) : ''
    form[`${prefix}Street`] = address.length >= 4 ? this.findRegionName(address[3]) : ''
  }

  // 回显地址数据到级联选择器
  setFormAddress(form, provinceName, cityName, districtName, streetName, addressField = 'nativeAddress') {
    const codes = this.findAddressCodes(provinceName, cityName, districtName, streetName)
    form[addressField] = codes
  }
}

export default new AreaService()